package org.example;

import bean.DB;
import bean.ResponseUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
@WebServlet("/updateCartItemQuantityServlet")

public class updateCartItemQuantityServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取当前用户ID和订单ID
        String userIdStr = (String) request.getSession().getAttribute("userId");
        String orderIdStr = request.getParameter("orderId");
        String quantityStr = request.getParameter("quantity");

        if (userIdStr == null || orderIdStr == null || quantityStr == null) {
            // 参数为空时，直接返回错误提示
            ResponseUtils.sendResponse(response, "无效的请求，缺少必要参数", "cart.jsp");
            return;
        }

        Integer userId = null;
        Integer orderId = null;
        Integer quantity = null;

        try {
            // 转换为整型数据
            userId = Integer.parseInt(userIdStr);
            orderId = Integer.parseInt(orderIdStr);
            quantity = Integer.parseInt(quantityStr);
        } catch (NumberFormatException e) {
            // 如果转换失败，返回错误提示
            ResponseUtils.sendResponse(response, "无效的参数格式", "cart.jsp");
            return;
        }

        // 检查数量是否合法，确保数量为正整数
        if (quantity <= 0) {
            ResponseUtils.sendResponse(response, "商品数量必须大于零", "cart.jsp");
            return;
        }

        // 创建数据库连接
        DB db = new DB();
        String query = "UPDATE usercart SET quantity = ? WHERE user_id = ? AND order_id = ?";

        try (Connection conn = db.createConn(); PreparedStatement pstmt = conn.prepareStatement(query)) {
            pstmt.setInt(1, quantity);
            pstmt.setInt(2, userId);
            pstmt.setInt(3, orderId);

            int rowsAffected = pstmt.executeUpdate();

            if (rowsAffected > 0) {
                // 如果更新成功，提示用户并跳转
                ResponseUtils.sendResponse(response, "购物车数量更新成功", "cart.jsp");
            } else {
                // 如果没有找到该商品记录
                ResponseUtils.sendResponse(response, "未找到该商品", "cart.jsp");
            }

        } catch (SQLException e) {
            // 处理数据库异常
            e.printStackTrace();
            ResponseUtils.sendResponse(response, "操作失败，数据库错误", "cart.jsp");
        }
    }
}
